<template>
  <div class="dataSource">
    <el-divider content-position="left">
      <i></i>数据来源
    </el-divider>
    <el-form ref="form" :model="dataSource" :rules="formRules" label-width="120px">
      <el-form-item label="文件类型" prop="fileType">
        <el-select v-model="dataSource.fileType" clearable placeholder="请选择" style="width: 220px">
          <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择文件" prop="fileName">
        <el-input v-model="dataSource.fileName" style="width: 220px" placeholder="请输入"></el-input>
        <input ref="uploadFile" style="display: none" :accept="acceptFileType" type="file" @change="handeFileChange" />
        <el-button @click="hanldeBrowseFile" size="small" type="primary" style="margin-left: 15px">浏览文件</el-button>
      </el-form-item>
      <el-form-item></el-form-item>
    </el-form>
    <el-divider content-position="left">
      <i></i>字段列表
    </el-divider>
    <div class="tableBox">
      <znxdListModify v-model="dataSource.multilistData" :formColumn="selectionFormColumn" :initData="tablesData" mode="addAndDelete"></znxdListModify>
    </div>
  </div>
</template>
<script>
import { getExcelFirstRow } from "@/api/task/dataFile.js"
import znxdListModify from "../dataFile/listModify"
export default {
  components: {
    znxdListModify
  },
  data() {
    return {
      tablesData: [
      ],
      gridData: [
      ],
      defaultProps: {
        children: "children",
        label: "label"
      },
      dataSource: {},
      // 数据库类型字典
      typeOptions: [
        {
          label: "excel",
          value: 1
        },
        {
          label: "csv",
          value: 2
        }
      ],
      page: {
        pageNo: 1, // 当前位于哪页
        pageSize: 8, // 1页显示多少条
        total: 0
      },
      selectionFormColumn: [
        {
          type: "input",
          name: "columnName",
          label: "字段名称"
        },
        {
          type: "input",
          name: "columnMemo",
          label: "字段别名"
        },
        {
          type: "input",
          name: "columnType",
          label: "字段类型"
        },
        {
          type: "input",
          name: "columnLong",
          label: "字段长度"
        },
        {
          type: "select",
          name: "isPrimary",
          label: "是否主键",
          options: [
            {
              label: "是",
              value: 1
            },
            {
              label: "否",
              value: 0
            }
          ]
        },
        {
          type: "select",
          name: "isAuto",
          label: "是否自增",
          options: [
            {
              label: "是",
              value: 1
            },
            {
              label: "否",
              value: 0
            }
          ]
        },
        {
          type: "select",
          name: "isNull",
          label: "允许为空",
          options: [
            {
              label: "是",
              value: 1
            },
            {
              label: "否",
              value: 0
            }
          ]
        }
      ],
      // 列表配置
      column: [
        {
          align: "center",
          name: "columnName",
          label: "字段名称"
        },
        {
          align: "center",
          name: "columnMemo",
          label: "字段别名"
        },
        {
          align: "center",
          name: "columnType",
          label: "字段类型"
        },
        {
          align: "center",
          name: "columnLong",
          label: "字段长度"
        }
      ],
      initSelection: [],
      // 多表选择
      tableSourceData: [],
      // initTableSourceData: []
      formRules: {}
    }
  },
  props: {
    initData: Object,
    mode: String
  },
  computed: {
    acceptFileType() {
      let type
      if (this.dataSource.fileType === 1) {
        type = ".xls,.xlsx"
      } else if (this.dataSource.fileType === 2) {
        type = ".csv"
      } else {
        type = ".csv,.xls,.xlsx"
      }
      return type
    }
  },
  watch: {
    dataSource: {
      deep: true,
      handler: function (val) {
        this.$emit("input", val)
      }
    },
    initData: {
      deep: true,
      handler: async function (obj) {
        let fileType = obj.fileType === 0 ? 1 : null;
        this.dataSource = {
          fileType: fileType,
          fileName: obj.fileName
        }
        this.tablesData = obj.readerColumns
        this.dataSource.selection = obj.readerColumns
        let _this = this;
        setTimeout(function () {
          _this.$refs.form.clearValidate();// 消除校验,这里的setTimeOut不能去掉,去掉之后会不生效
        }, 30);
      }
    }
  },
  methods: {
    hanldeBrowseFile() {
      if (!this.dataSource.fileType) {
        return
      }
      this.$refs.uploadFile.click()
    },
    handeFileChange(e) {
      let file = e.target.files[0]
      // this.dataSource.fileName = "file.name"
      let fileName = e.target.files[0].name
      this.dataSource.fileName = fileName
      this.dataSource.file = file
      this.$confirm("第一行数据否作为存入数据库的字段行?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let param = new FormData()
        param.append("file", file)
        let fileType = this.dataSource.fileType
        this.dataSource.firstColum = 1
        param.append("fileType", fileType)
        getExcelFirstRow(param)
          .then((res) => {
            let data = res.data
            if (data.code === 200) {
              let tablesData = []
              data.content.forEach((item, index) => {
                tablesData.push({
                  columnName: item,
                  columnMemo: "",
                  columnType: "varchar",
                  columnLong: "255",
                  isPrimary: 0,
                  isAuto: 0,
                  isNull: 1
                })
              })
              this.tablesData = tablesData
              this.dataSource.multilistData = tablesData
              this.dataSource.selection = tablesData
              this.$message({
                message: data.msg || "操作成功",
                type: "success"
              })
            } else {
              this.$message({
                message: data.msg,
                type: "error"
              })
            }
          })
          .catch(() => {
            // this.$message.error(error);
            this.$message({
              message: "操作失败",
              type: "error"
            })
          })
      }).catch(() => {
        this.dataSource.firstColum = 2
        this.$message({
          type: "info",
          message: "已取消操作"
        })
        let param = new FormData()
        param.append("file", file)
        let fileType = this.dataSource.fileType
        param.append("fileType", fileType)
        getExcelFirstRow(param)
          .then((res) => {
            let data = res.data
            if (data.code === 200) {
              let tablesData = []
              data.content.forEach((item, index) => {
                tablesData.push({
                  columnName: item,
                  columnMemo: "",
                  columnType: "varchar",
                  columnLong: "255",
                  isPrimary: 0,
                  isAuto: 0,
                  isNull: 1
                })
              })
              this.tablesData = tablesData
              this.dataSource.multilistData = tablesData
              this.dataSource.selection = tablesData
              this.$message({
                message: data.msg || "操作成功",
                type: "success"
              })
            } else {
              this.$message({
                message: data.msg,
                type: "error"
              })
            }
          })
          .catch(() => {
            // this.$message.error(error);
            this.$message({
              message: "操作失败",
              type: "error"
            })
          })
      })
    },
    handleGetSelection(data) {
      this.dataSource = {
        ...this.dataSource,
        selection: data
      }
    },
    // 校验数据
    validateForm() {
      let flag = true

      this.$refs.form.validate((valid) => {
        if (valid) {
          flag = true
        } else {
          flag = false
          return flag;
        }
      })

      if (!this.dataSource.fileType || !this.dataSource.fileName || !this.dataSource.file) {
        flag = false
        this.$message({
          message: "数据源不能为空",
          type: "error"
        })
        return flag
      }


      return flag
    },
    setRules() {
      this.formRules = {
        fileType: [{ required: true, message: "不能为空" }],
        fileName: [{ required: true, message: "不能为空" }],
        file: [{ required: true, message: "不能为空" }]
      }
    }
  },
  mounted() {
    this.setRules()
  }
};
</script>
<style lang="scss" scoped>
.dataSource {
  .el-divider__text.is-left {
    left: 0;
    display: flex;
    flex-direction: row;
    > i {
      display: block;
      width: 3px;
      height: 14px;
      background: #128df3;
      margin-right: 5px;
    }
  }
  .tableBox {
    padding-left: 40px;
  }
  .transfer {
    width: 600px;
    // max-height: 420px;
    // border: 1px solid red;
  }
}
</style>
<style lang="scss">
.dataSource {
  .transfer {
    .el-transfer-panel__body {
      height: 346px;
    }
    .el-transfer-panel__list {
      height: 300px;
    }
  }
}
</style>
